
var $voiceidone="";
var serceridone = '';
var localId = '';
var serverId = '';
var images = {
    localId: [],
    serverId: []
};
wx.config({
    debug: false,
    appId: '<?php echo $this->signPackage["appId"];?>',
    timestamp: '<?php echo $this->signPackage["timestamp"];?>',
    nonceStr: '<?php echo $this->signPackage["nonceStr"];?>',
    signature: '<?php echo $this->signPackage["signature"];?>',
    jsApiList: [
        'startRecord',
        'stopRecord',
        'onRecordEnd',
        'playVoice',
        'pauseVoice',
        'stopVoice',
        'uploadVoice',
        'downloadVoice',
        'chooseImage',
        'previewImage',
        'uploadImage',
        'downloadImage',
        'onVoiceRecordEnd'
    ]
});

wx.ready(function(){
    wx.hideOptionMenu(); //隐藏右上角菜单接口
});

var u = navigator.userAgent, app = navigator.appVersion;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android终端或者uc浏览器
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

var userid = $('#userid').val(); //get user id
var headpic = $('#headpic').val(); //get user 头像
var username = $('#username').val(); //get user 头像
var 课程id = ""; //get 课程id
var 群id = $('#群id').val(); //get 群id


//create a new WebSocket object.
//var wsUri = "ws://<?//= G_websocket接口.":".G_websocket端口."/".G_websocket地址?>///server.php";
var wsUri = "ws://<?= G_websocket接口.":".G_websocket端口?>";
websocket = new ReconnectingWebSocket(wsUri);
websocket.onopen = function(ev) { // connection is open
    $('#message_box').append("<div class=\"system_msg\"></div>");
    var msg = {
        type: 'login',
        userid: userid,
        headpic: headpic,
        username: username,
        课程id: 课程id,
        群id: 群id,
    };
    //convert and send data to server
    websocket.send(JSON.stringify(msg));
    //notify user
};

// 聊天发送
$('.send-btn').click(function(){ //use clicks message send button
    var serverId = '';
    var mymessage = $('#message').val(); //get message text

    $.post('<?=$this->url('group','judge_user_group')?>',{'群id':'<?= $_GET['groupId']?>'},function(data){
        if(data>0){
            if(mymessage == "" || mymessage == null || mymessage == " "){ //emtpy message?
                alert("请输入文字!");
            }
            if(mymessage != "" && mymessage!=" " && mymessage!=null){
                $.post('business/agent_manages.php',{'message':mymessage,"userid":userid,"serverId":serverId,'headpic':headpic,"群id":群id,'参数':'群聊'},function(data){
                    var 地址="";
                    var msg = {
                        type: 'usermsg',
                        message: mymessage,
                        userid: userid,
                        headpic: headpic,
                        username: username,
                        课程id: 课程id,
                        群id: 群id,
                        serverId:serverId,
                        地址:地址,
                    };

                    websocket.send(JSON.stringify(msg));
                });
                $("#message").focus();
                $("#message").attr("autofocus","autofocus");
                $("#message").val("");
                footerfunction();
            }
        }
    });
});

websocket.onmessage = function(ev) {
    var msg = JSON.parse(ev.data); //PHP sends Json data
    var type = msg.type; //message type
    var uid = msg.userid; //user name
    var upic = msg.headpic; //user name
    var uname = msg.username; //user name
    var u课程id = msg.课程id; //user name
    var u群id = msg.群id; //user name
    var userver = msg.serverId; //message text
    var 群id = $('#群id').val();
    var userid = $('#userid').val(); //get user id
    var umsg = msg.message; //message text
    var u地址 = msg.地址; //message text
    if(u群id!=""){
        if(u群id==群id){
            if(type == 'usermsg') {
                if(userver!=""){
                    if(uid==userid){
                        $('#message_box').append('<div class="chat-item-m"> <div class="style2"><div class="chat-item-img"><img  src="'+upic+'"></div></div><div class="chat-item-contr"><span class="font" onclick="bofang(\''+userver+'\')" ><span id="'+userver+'" ok1="0"><img  src="business/style/xiaohongdian.gif" alt=""></span ><img style="padding-top:3px;" src="business/style/yuyincont2.gif" alt=""></span></div><div class="clear"></div></div>')
                    }else{
                        $('#message_box').append('<div class="chat-item-o"><div class="style1"><div class="chat-item-img"><img src="'+upic+'"></div></div><div class="chat-item-contl"><div class="name">'+uname+'</div><span class="font" onclick="bofang(\''+userver+'\')"><img src="business/style/yuyincont.gif" style="padding-top:3px;" alt=""><span id="'+userver+'" ok1="0"><img  src="business/style/xiaohongdian.gif" alt=""></span></span></div><div class="clear"></div></div>')
                    }
                 }else if(umsg!=""){
                    if(uid==userid){
                        $('#message_box').append('<div class="chat-item-m"><div class="style2"><div class="chat-item-img"><img src="'+upic+'" ></div></div><div class="chat-item-contr"><span class="font">'+ umsg +'</span></div><div class="clear"></div></div>')
                    }else{
                        $('#message_box').append('<div class="chat-item-o"><div class="style1"><div class="chat-item-img"><img src="'+upic+'" ></div></div><div class="chat-item-contl"><div class="name">'+uname+'</div><span class="font">'+ umsg +'</span></div><div class="clear"></div></div>')
                    }
                }else if(u地址!=""){
                    var dizhi="http://<?php echo $_SERVER['HTTP_HOST']?>/Ram_disk/img/"+u地址;
                    if(uid==userid){ //                             $('#message_box').append('<div>'+dizhi+'</div><img src="'+dizhi+'" width=300>');
                        $('#message_box').append('<div class="chat-item-m" ><div class="style2"><div class="chat-item-img"><img src="'+upic+'" style="overflow:hidden;"></div></div><div class="chat-item-contr" style=""><span class="font"><img src="'+dizhi+'" style="height:100px;" onclick="imgbig(this)"></span></div><div class="clear"></div></div>')
                    }else{
                        $('#message_box').append('<div class="chat-item-o"><div class="style1"><div class="chat-item-img"><img src="'+upic+'" ></div></div><div class="chat-item-contl"  style=""><div class="name">'+uname+'</div><span class="font"><img src="'+dizhi+'" style="height:100px;" onclick="imgbig(this)"></span></div><div class="clear"></div></div>')
                    }
                }
                footerfunction();
            }  else if (type == 'ping') {
                websocket.send('{"type":"pong"}');
            }
        }
    }
};

websocket.onerror   = function(ev){
//$('#message_box').append("<div class='chat-time'>由于您的网络原因,连接断开,请退出后重新进入.</div>");
};

websocket.onclose = function(ev) {
//$('#message_box').append("<div class='chat-time'>连接断开,请退出后重新进入.</div>");
};



function myClose(){
    websocket.onclose();
};

window.onunload = myClose;

function ping_websock() {
    websocket.send('{"type":"pong"}');
};

setTimeout(setInterval('ping_websock()', 10000), 10000);

function blurover(){
    $(".txtsendbg").delay(300).hide(1);
    $(".txtsendcontent").delay(300).hide(1);
    footerfunction();
    $(".class_talk_con_header").show();
};

 $(".class_talk_con_header").click(function(){
        $(".class_talk_con_header video").show();
});

$(".class_talk_con_header_ts").click(function(){
    $(".class_talk_con_header").click(function(){
        $(".class_talk_con_header video").show();
    })
});

$(".class_talk_con_footer_icon_txt")[0].addEventListener('click',function(ev){
    $("#message")[0].focus()
});

function closetxtsend1(){
    $(".txtsendbg").hide();
    $(".txtsendcontent").hide();
    footerfunction();
    $(".class_talk_con_header").show();
};

 function closetxtsend(){
    $(".txtsendbg").hide();
    $(".txtsendcontent").hide();
    footerfunction();
    $(".class_talk_con_header").show();
};

function funtxtsend(){
    $(".txtsendbg").show(function(){
        $("#message").focus();
    });
    $(".txtsendcontent").show();
    if(isAndroid){
        $(".class_talk_con_header").hide();
    }
};

 function qwertyui(){
    $("#class_talk_con_footer_frame").addClass("audio_xx");
    $(".m_hide").show();
    $(".m_show").hide();
    $(".closeabs").show();
};

function chatyl(){
    $(".closeabs").hide();
    $("#class_talk_con_footer_frame").removeClass("audio_xx");
    $(".m_show").show();
    $(".m_hide").hide();
    if(!$(".class_talk_con_footer_icon_audio_on").attr("luyin")){
        stopluyin1();
    };
    $(".time-bg").hide();
    $(".class_talk_con_footer_icon_audio_on").show();
    $(".class_talk_con_footer_icon_audio_off").hide();
    clearTimeout(dingshi)
};

function sendover(){
    $("#qq").hide();
    $(".txtsendbg").hide();
    $(".txtsendcontent").hide();
    footerfunction();
    $(".class_talk_con_header").show();
};

function footerfunction(){
    e1=document.getElementById("big-chat");
    h=e1.scrollHeight;
    document.documentElement.scrollTop=h;
    window.pageYOffset =h;
    document.body.scrollTop=h;
};

function playaudio($voiceid){
    if($("#"+$voiceid)[0].paused) {
        $("#"+$voiceid)[0].play();
    } else {
        $("#"+$voiceid)[0].pause();
    }
    wx.stopVoice({
        localId: localId
    });
    $("#"+serceridone).attr("ok1",0);
    if($voiceidone.length>0){
      if(!$("#"+$voiceidone)[0].paused){
            $("#"+$voiceidone)[0].pause();
            $("#"+$voiceidone)[0].currentTime=0;
        }
    }
     $voiceidone = $voiceid
};

function 显示二维码(){
    $.post('business/agent_manages.php',{'群id':"<?= $_GET['groupId']?>","参数":'生成群二维码'},function(data){
        if(data){
            $('#show_ewm').show();
            var  显示 ='<img  src="cache/wxqrcode/'+data+'.jpg" alt="">';
            $('#show_erweim').html(显示);
        }else {
            alert("显示失败!");
        }
    });
};


function hidens(num){
    $('#'+num).hide();
};

function imgbig(obj){
    if(isAndroid){
        $(".class_talk_con_header video").hide();
    }
    $("#imgbbig").show();
    var img=$(obj).attr('src');
    $(".pinch-zoom").find("img").attr("src",img);
};

function imgbigclose(){
    $(".class_talk_con_header video").show();
    $("#imgbbig").hide();
};

function show123(变量) {
    $(".time").text(变量+"s");
    var now=变量-1;
   if(parseInt(变量) >0){
        dingshi=setTimeout(function () {
            show123(now);
        }, 1000);
    }
};

function qungroup(){
    $("#qun-group-bg").show();
    $("#qun-group").show();
};

function qungrouphide(){
    $("#qun-group-bg").hide();
    $("#qun-group").hide();
};

function xianshi(num2,num){
    if(num2==1){
        $(".time-bg").show();
        $(".class_talk_con_footer_icon_audio_off").show();
        $(".class_talk_con_footer_icon_audio_on").hide();
        $(".floorbg").show();
        startluyin();
        setTimeout(show123(num),1000);
        auto_stop();
        $(".class_talk_con_footer_icon_audio_on").attr("luyin",1);
    }else{
        $(".time-bg").hide();
        $(".class_talk_con_footer_icon_audio_on").show();
        $(".class_talk_con_footer_icon_audio_off").hide();
        $(".floorbg").hide();
        clearTimeout(dingshi);
        stopluyin();
        $(".class_talk_con_footer_icon_audio_on").attr("luyin",0);
        footerfunction();
        $("#class_talk_con_footer_frame").removeClass("audio_xx");
        $(".m_show").show();
        $(".m_hide").hide();
        $(".closeabs").hide();
    }
};

function bofang(serverId){
    if (serverId == '') {
        alert('请先使用 uploadVoice 上传声音');
        return;
    }
    hidens(serverId);
    wx.downloadVoice({
    serverId: serverId,
    success: function (res) {
        localId = res.localId;
        if($("#"+serverId).attr("ok1")==0){
            wx.playVoice({
                localId: localId
            });
            $("#"+serverId).attr("ok1",1);
            }else{
                wx.pauseVoice({
                    localId: localId
                });
                $("#"+serverId).attr("ok1",0);
            }
        }
    });
    $("#"+$voiceidone)[0].pause();
    $("#"+$voiceidone)[0].currentTime=0;
    if(serceridone.length>0){
         wx.stopVoice({
            localId: localId
        });
        $("#"+serceridone).attr("ok1",0);
    }
    serceridone = serverId;
};

function stopluyin(){
    wx.stopRecord({
        success: function (res) {
            send_record(res)
        },
        fail: function (res) {
            alert(JSON.stringify(res));
        }
    });
};

function auto_stop(){
    wx.onVoiceRecordEnd({
        // 录音时间超过一分钟没有停止的时候会执行 complete 回调
        complete: function (res) {
            send_record(res);
            chatyl();
        }
    });
};

function stopluyin1(){
    wx.stopRecord({
        success: function (res) {
            localId = res.localId;
        },
        fail: function (res) {
            alert(JSON.stringify(res));
        }
    });
}

 //发送录音
function send_record(res){
    localId = res.localId;
    wx.uploadVoice({
        localId: localId,
        success: function (res) {
            serverId = res.serverId;
            var userid = $('#userid').val(); //get user id
            var headpic = $('#headpic').val(); //get user 头像
            var username = $('#username').val(); //get user 头像
            var 群id = $('#群id').val(); //get 课程id
            var 课程id = ""; //get 课程id
            var 地址 = ""; //get 课程id
            var message = ""; //get 课程id
            $.post('business/agent_manages.php',{'serverId':serverId,'message':message,"userid":userid,'headpic':headpic,"群id":群id,'参数':'群聊'},function(data){
                var msg = {
                    type: 'usermsg',
                    serverId: serverId,
                    userid: userid,
                    message: message,
                    headpic: headpic,
                    username: username,
                    课程id: 课程id,
                    群id:群id,
                    地址:地址,
                };
                websocket.send(JSON.stringify(msg));
            });
        }
    });
};

function uploadimgclose(){
    $(".uploadimg11").hide();
};

function fun11111(num3){
    if(num3==1){
        $("footer .input-btn12").children().attr("src","business/style/jianpan.gif");
        $(".wenzi").hide().next().show();
    }else{
        $(".yuyin").hide().prev().show();
        $("footer .input-btn11").children().attr("src","business/style/shuohua.gif");
    }
};

function startluyin(){
    wx.startRecord({
        cancel: function () {
            alert('用户拒绝授权录音');
        }
    });
};

function uploadimg(){
    if(isAndroid){
        $(".class_talk_con_header video").hide();
    }
    wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
            $(".class_talk_con_header video").show();
            localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
            syncUpload(localIds);
        }
    });
};

function syncUpload(localIds){
    var localId = localIds.pop();
    wx.uploadImage({
        localId: localId,
        isShowProgressTips: 1,
        success: function (res) {
            var imageId = res.serverId; // 返回图片的服务器端ID
            var userid = $('#userid').val(); //get user id
            var headpic = $('#headpic').val(); //get user 头像
            var username = $('#username').val(); //get user 头像
            var 课程id = ""; //get 课程id
            var 群id = $('#群id').val(); //get 群id
            // alert(群id);
            $.post('business/agent_manages.php',{'imageId':imageId,"userid":userid,"群id":群id,'参数':'群聊'},function(data){
            var serverId="";//语音
            var message="";//语音
            var msg = {
                type: 'usermsg',
                serverId: serverId,
                userid: userid,
                message: message,
                headpic: headpic,
                username: username,
                课程id: 课程id,
                群id:群id,
                地址:data
                };
                websocket.send(JSON.stringify(msg));
            })
        }
    });
};

function 查看历史(){
    var page = $('#查询起始值').val();
    $.ajax({
        url:"business/agent_manages.php",
        type:'post',
        async:false,
        data:{参数:'查看群历史消息',page:page,群id:'<?=$_GET['groupId']?>',时间:'<?=date("Y-m-d H:i:s")?>'},
        datatype:'json',
        success:function(data){
            // alert(data)
            json = eval(data);
            str ='';
            var 前一时间 ='2016/01/01 00:00:00';

            for(var i=0; i<json.length; i++) {
                if(i>0){
                    前一时间 = json[i-1].时间;
                }
                前一时间2=  前一时间.replace(/\-/g, "/") ;
                当前时间2 = json[i].时间.replace(/\-/g, "/") ;
                var t1=new Date(前一时间2);
                var t2=new Date(当前时间2);
                var s=(t2.getTime()-t1.getTime());//毫秒
                s=(s/(1000*60));
                if(s>1){
                    str+="<div class='chat-time'>"+当前时间2+"</div>";
                }
                if(json[i].result2){
                    str+='<p>'+json[i].result2+'</p>';
                    $('#show123').remove();
                    $('#查询起始值').remove();
                    $(".class_talk_con_header_history").remove();
                }
                var 图像="cache/card_img/top_index.jpg";
                if(json[i].头像 !=''){
                    图像 = json[i].头像;
                }
                var 本用户 ='<?=$_SESSION['vo用户数据']['id']?>';
                if(json[i].聊天类型=='语音'){
                    if( 本用户 == json[i].用户id){
                        str+='  <div class="chat-item-m" style=""><div class="style2"><div class="chat-item-img"><img style="width:40px;padding-top:3px;height:40px;border-radius: 20px;" src="'+图像+'"  ></div></div><div class="chat-item-contr"><span class="font" > <span><img onclick="playaudio(\''+json[i].serverid+'\')" style="padding-top:3px;" src="business/style/yuyincont2.gif" alt=""> <audio  id="'+json[i].serverid+'" src="http://<?php echo $_SERVER['HTTP_HOST']?>/Ram_disk/'+json[i].serverid+'.mp3" ></audio></span></span> </div><div class="clear"></div></div>';
                    }else{
                        str+=' <div class="chat-item-o" style=""><div class="style1"><div class="chat-item-img"><img class="abc" style="width:40px;height:40px;border-radius: 20px;" src="'+图像+'" style="padding-top:3px;"></div></div><div class="chat-item-contl"><div class="name">'+json[i].name+'</div><span class="font"> <img onclick="playaudio(\''+json[i].serverid+'\')" src="business/style/yuyincont.gif" style="padding-top:3px;" alt=""><span><audio  id="'+json[i].serverid+'" src="http://<?php echo $_SERVER['HTTP_HOST']?>/Ram_disk/'+json[i].serverid+'.mp3" ></audio></span> </span> </div><div class="clear"></div></div>';
                    }
                }
                else if(json[i].聊天类型=='文本'){
                    if( 本用户 == json[i].用户id){
                        str+='  <div class="chat-item-m" style=""><div class="style2"><div class="chat-item-img"><img  style="width:40px;height:40px;border-radius: 20px;" src="'+图像+'" ></div></div><div class="chat-item-contr"><span class="font font-right">'+json[i].聊天内容+'</span></div><div class="clear"></div></div>';
                    }else{
                        str+='  <div class="chat-item-o" style=""><div class="style1"><div class="chat-item-img"><img   style="width:40px;height:40px;border-radius: 20px;" src="'+图像+'"></div></div><div class="chat-item-contl"><div class="name">'+json[i].name+'</div><span class="font font-left">'+json[i].聊天内容+'</span></div><div class="clear"></div></div>';
                    }
                }
                else if(json[i].聊天类型=='图片'){
                    if( 本用户 == json[i].用户id){
                        str+='  <div class="chat-item-m" style=""><div class="style2"><div class="chat-item-img"><img  style="width:40px;height:40px;border-radius:20px;" src="'+图像+'" ></div></div><div class="chat-item-contr"><span class="font font-right"><img src="http://<?php echo $_SERVER['HTTP_HOST']?>/Ram_disk/img/'+json[i].地址+'"style="height:100px;" onclick="imgbig(this)"/></span></div><div class="clear"></div></div>';
                    }else{
                        str+='  <div class="chat-item-o" style=""><div class="style1"><div class="chat-item-img"><img   style="width:40px;height:40px;border-radius:20px;" src="'+图像+'"></div></div><div class="chat-item-contl"><div class="name">'+json[i].name+'</div><span class="font font-left"><img src="http://<?php echo $_SERVER['HTTP_HOST']?>/Ram_disk/img/'+json[i].地址+'"style="height:100px;" onclick="imgbig(this)"/></span></div><div class="clear"></div></div>';
                    }
                }
            }
            $(str).prependTo("#message_box");
            if($(str)){
                $(".class_talk_con_header_history").show();
            }
            $('#查询起始值').val(page*1 + 1);
        }
    })
};

// 进入直接到最底部

查看历史();
window.onload = function(){
    footerfunction();
}